﻿using System;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Infrastructure.Security.Md5
{
    /// <summary>
    /// md5工具类
    /// </summary>
    public static class Md5Helper
    {
        private static readonly string Salt;

        static Md5Helper()
        {
            Salt = ConfigurationManager.AppSettings["Md5Salt"] ?? "wm73UZkS";
        }

        /// <summary>
        /// MD5密码加密
        /// md5+加盐+md5
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string GetMd5EncryptPassword(this string password)
        {
            return Md5Encrypt($"{Md5Encrypt(password)}{Salt}");
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns></returns>
        public static string Md5Encrypt(this string data)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                byte[] fromData = Encoding.UTF8.GetBytes(data);
                byte[] targetData = md5.ComputeHash(fromData);
                StringBuilder sb = new StringBuilder(targetData.Length);

                foreach (var t in targetData)
                {
                    sb.Append(t.ToString("x2"));
                }

                return sb.ToString();
            }
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="data">byte数组</param>
        /// <returns></returns>
        public static string Md5Encrypt(this byte[] data)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                // byte[] fromData = Convert.ToByte(data);
                byte[] targetData = md5.ComputeHash(data);
                StringBuilder sb = new StringBuilder(targetData.Length);

                foreach (var t in targetData)
                {
                    sb.Append(t.ToString("x2"));
                }

                return sb.ToString();
            }
        }

        /// <summary>
        /// md5加盐
        /// </summary>
        /// <param name="data">字符串</param>
        /// <param name="salt">盐</param>
        /// <returns></returns>
        public static string Md5EncryptAndSalt(this string data, string salt = "")
        {
            salt = string.IsNullOrEmpty(salt) ? Salt : salt;
            return Md5Encrypt($"{data}{salt}");
        }
    }
}
